desc 'Launch everything for the CAS example'
task :launch do
  processes = []

  Dir.chdir('..') do
    unless ENV['CAS_BASE']
      processes << fork { sh "bundle exec rackup cas/rubycas_server.ru" }
      ENV['CAS_BASE'] = 'http://localhost:9697'
    else
      $stderr.puts "Using existing CAS server #{ENV['CAS_BASE']}"
    end
    processes << fork { sh "bundle exec rackup cas/fortune_server.ru" }
    unless ENV['CAS_CALLBACK']
      processes << fork { ruby "-rubygems cas/cas_proxy_callback.rb" }
      ENV['CAS_CALLBACK'] = 'https://localhost:9698'
    else
      $stderr.puts "Using existing proxy callback #{ENV['CAS_CALLBACK']}"
    end
    processes << fork { ruby "-rubygems cas/fortune_client.rb" }
  end

  trap('INT') { Process.kill('TERM', *processes) }

  Process.waitall
end

desc 'Reset CAS server state'
task :clean do
  rm_rf Dir['var/*']
end

desc "Recreates the java keystore containing the certificate for this example"
task :keystore => "localhost.jks"

file "localhost.jks" => ["localhost.crt"] do |t|
  rm_f t.name
  cert = t.prerequisites.first
  sh "keytool -import -file '#{cert}' -alias localhost " <<
    "-keystore '#{t.name}' -storepass changeit -noprompt"
end

task :default => :launch
